<?php
/**
 * Created by PhpStorm.
 * User: lyon
 * Date: 16-12-6
 * Time: 下午12:39
 */
include_once 'Curler.php';
include_once 'Config.php';
include_once 'Log.php';
include_once 'Count.php';

class Preg
{
    public static $table;
    /**
     * @param $searchName
     * @return bool
     * 进入用户搜索界面
     */
    public static function searchUser($searchName)
    {
        $url = 'http://s.weibo.com/user/' . urlencode($searchName) . '&Refer=SUer_box';
        $outPut = Curler::request('GET', $url);
        file_put_contents(Log::$LOG['logfile'],  date('Y-m-d H:i:s') . ':正在搜索用户' . $searchName . PHP_EOL, FILE_APPEND);
        $link = self::getSearchLink($outPut, $searchName); //获取到用户主页地址
        if (!empty($outPut))
        {
            file_put_contents( './data/' . $searchName . '.html', $outPut);
            Count::success();
        }
        file_put_contents(Log::$LOG['logfile'],  date('Y-m-d H:i:s') . ':保存用户' . $searchName . '的搜索界面信息成功' . PHP_EOL, FILE_APPEND);
        if (!empty($link))
        {
            self::getAllInfo($link, $searchName); //获取用户主页信息
            return true;
        }
        else
        {
            file_put_contents(Log::$LOG['logfile'],  date('Y-m-d H:i:s') . ':用户' . $searchName . '的搜索界面信息失败正在回退' . PHP_EOL, FILE_APPEND);
            Preg::rollBackUser($searchName);
            Count::error();
            return false;
        }
    }
    public static function getUserInfo($searchName)
    {

        $user = [];
        $name = './data/' . $searchName . '_home.html';
        if (is_file($name)) {
            $pre = array(" ", "　", "\t", "\n", "\r", "\\r", "\\t", "\\n");
            $rep = array('', '', '', '', '', '');
            $data = str_replace($pre, $rep, file_get_contents($name));

            $uname = '/<title>.*<\/title>/';
            preg_match($uname, $data, $uinfo);
            $uinfo = implode('', $uinfo);
            //var_dump( str_replace('的微博_微博', '', strip_tags($uinfo)));
            $uinfo = str_replace('的微博_微博', '', strip_tags($uinfo));
            $user['n_name'] = $uinfo;


            $guan = '/<strong class=\\\".{0,10}\\\">[0-9]*<\\\\\/strong><span class=\\\".{0,10}\\\">关注<\\\\\/span>/x';
            preg_match($guan, $data, $uinfo);
            $uinfo = implode('', $uinfo);
            //var_dump(str_replace('关注', '', strip_tags($uinfo)));
            $uinfo = str_replace('关注', '', strip_tags($uinfo));
            $user['attention'] = empty($uinfo) ? 0 : $uinfo;


            $fen = '/<strong class=\\\".{0,10}\\\">[0-9]*<\\\\\/strong><span class=\\\".{0,10}\\\">粉丝<\\\\\/span>/x';
            preg_match($fen, $data, $uinfo);
            $uinfo = implode('', $uinfo);
            //var_dump(str_replace('粉丝', '', strip_tags($uinfo)));
            $uinfo = str_replace('粉丝', '', strip_tags($uinfo));
            $user['fans'] = empty($uinfo) ? 0 : $uinfo;


            $wei = '/<strong class=\\\".{0,10}\\\">[0-9]*<\\\\\/strong><span class=\\\".{0,10}\\\">微博<\\\\\/span>/x';
            preg_match($wei, $data, $uinfo);
            $uinfo = implode('', $uinfo);
            //var_dump(str_replace('微博', '', strip_tags($uinfo)));
            $uinfo = str_replace('微博', '', strip_tags($uinfo));
            $user['weibo_count'] = empty($uinfo) ? 0 : $uinfo;

            if ($user['attention'] == 0 || $user['fans'] == 0 || $user['weibo_count'] == 0) {
                $name = './data/' . $searchName . '_detail.html';
                if (is_file($name)) {
                    $pre = array(" ", "　", "\t", "\n", "\r", "\\r", "\\t", "\\n");
                    $rep = array('', '', '', '', '', '');
                    $data = str_replace($pre, $rep, file_get_contents($name));


                    $guan = '/<strong class=\\\".{0,10}\\\">[0-9]*<\\\\\/strong><span class=\\\".{0,10}\\\">关注<\\\\\/span>/x';
                    preg_match($guan, $data, $uinfo);
                    $uinfo = implode('', $uinfo);
                    //var_dump(str_replace('关注', '', strip_tags($uinfo)));
                    $uinfo = str_replace('关注', '', strip_tags($uinfo));
                    $user['attention'] = empty($uinfo) ? 0 : $uinfo;


                    $fen = '/<strong class=\\\".{0,10}\\\">[0-9]*<\\\\\/strong><span class=\\\".{0,10}\\\">粉丝<\\\\\/span>/x';
                    preg_match($fen, $data, $uinfo);
                    $uinfo = implode('', $uinfo);
                    //var_dump(str_replace('粉丝', '', strip_tags($uinfo)));
                    $uinfo = str_replace('粉丝', '', strip_tags($uinfo));
                    $user['fans'] = empty($uinfo) ? 0 : $uinfo;


                    $wei = '/<strong class=\\\".{0,10}\\\">[0-9]*<\\\\\/strong><span class=\\\".{0,10}\\\">微博<\\\\\/span>/x';
                    preg_match($wei, $data, $uinfo);
                    $uinfo = implode('', $uinfo);
                    //var_dump(str_replace('微博', '', strip_tags($uinfo)));
                    $uinfo = str_replace('微博', '', strip_tags($uinfo));
                    $user['weibo_count'] = empty($uinfo) ? 0 : $uinfo;

                } else {
                    return array('issearch' => 0,);
                }
            }
            return $user;
        }
        else {
            return array('issearch' => 0,);
        }
    }
    /**
     *匹配搜索到的用户链接
     *
     */
    public static function getSearchLink($data, $searchName)
    {
        $link = [];
        //匹配链接
        $href = '/<a class=\\\"W_linkb\\\" target=\\\"_blank\\\" href=\\\"http:\\\\\/\\\\\/weibo.com(?:\\\\\/u)?\\\\\/(?:[0-9a-zA-Z]{0,40})\?refer_flag=1001030201_\\\\\" class=\\\"wb_url\\\" suda-data=\\\"key=tblog_search_user&value=user_feed_1_url\\\">http:\\\\\/\\\\\/weibo.com(?:\\\\\/u)?\\\\\/(?:[0-9a-zA-Z]{0,40})<\\\\\/a>/';
        preg_match($href, $data, $info);
        $info = implode('', $info);
        $urlArr = str_replace('\\', '', strip_tags($info));
        return $urlArr;
    }
    public static function getAllInfo($url, $searchName)
    {
        $outPut = Curler::request('GET', $url);
        file_put_contents(Log::$LOG['logfile'], date('Y-m-d H:i:s') . ':进入用户' . $searchName . '主页' . PHP_EOL, FILE_APPEND);
        if (!empty($outPut))
        {
            file_put_contents(Log::$LOG['logfile'], date('Y-m-d H:i:s') . ':保存用户' . $searchName . '主页信息成功' . PHP_EOL, FILE_APPEND);
            file_put_contents( './data/' . $searchName . '_home.html', $outPut);
            Count::success();
        }
        else
        {
            file_put_contents(Log::$LOG['logfile'], date('Y-m-d H:i:s') . ':保存用户' . $searchName . '主页信息失败正在回退' . PHP_EOL, FILE_APPEND);
            Preg::rollBackUser($searchName);
            Count::error();
        }
        $detail_link = Preg::getDetailLink($outPut); //获取用户详细信息地址
        if (!empty($detail_link))
        {
            file_put_contents(Log::$LOG['logfile'],  date('Y-m-d H:i:s') . ':用户' . $searchName . '详细界面获取成功' . PHP_EOL, FILE_APPEND);
            self::getDetailPage($detail_link, $searchName);
            return true;
        }else {
            file_put_contents(Log::$LOG['logfile'],  date('Y-m-d H:i:s') . ':用户' . $searchName . '详细界面获取失败，正在回退' . PHP_EOL, FILE_APPEND);
            Preg::rollBackUser($searchName);
            Count::error();
        }
    }
    public static function getDetailPage($pageId = [],$searchName)
    {
        $id = $pageId[0];
        $url = 'http://weibo.com/p/' . $pageId[0] . '/info?mod=pedit_more';
        $outPut = Curler::request('GET', $url);
        if (strpos($outPut, '404错误'))
        {
            file_put_contents(Log::$LOG['logfile'],  date('Y-m-d H:i:s') . ':正在更换ID为' . $id . '的用户主页URL' . PHP_EOL, FILE_APPEND);
//            echo '------------- 更换URL -----------------' . PHP_EOL;
            $url = 'http://weibo.com/' . $pageId[1] . '/about';
            $outPut = Curler::request('GET', $url);
            $id = $pageId[1];
        }
        file_put_contents(Log::$LOG['logfile'],  date('Y-m-d H:i:s') . ':正在写入ID为' . $id . '的用户' . PHP_EOL, FILE_APPEND);
        file_put_contents( './data/' . $searchName .'_detail.html', $outPut);
        file_put_contents(Log::$LOG['url'],  $searchName . ':' . $url . PHP_EOL, FILE_APPEND);
        file_put_contents(Log::$LOG['logfile'],  date('Y-m-d H:i:s') . ':ID为' . $id . '的用户写入成功' . PHP_EOL . PHP_EOL, FILE_APPEND);
        Count::success();
    }

    public static function getDetailLink($str)
    {
        $info = [];
        $preg ="/[$]CONFIG\\['page_id'\\]='([0-9]{1,25})';/i";
        preg_match($preg, $str, $info);
        $link[] = $info[1];
        $preg ="/[$]CONFIG\\['oid'\\]='([0-9]{1,25})';/i";
        preg_match($preg, $str, $info);
        $link[] = $info[1];
        return $link;
    }

    public static function rollBackUser($searchName, $status = 2)
    {
        $u_name = ['u_name' => "{$searchName}"];
        $issearch = ['issearch' => $status];
        if (Mysql::upDateOne($issearch, $u_name, $GLOBALS['db']['name']))
        {
            if ($status = 2)
            {
                file_put_contents(Log::$LOG['logfile'],  date('Y-m-d H:i:s') . ':用户' . $searchName . '回退成功' . PHP_EOL . PHP_EOL, FILE_APPEND);
            }
            else
            {
                file_put_contents(Log::$LOG['error'],  date('Y-m-d H:i:s') . ':用户' . $searchName . '的文件不存在' . PHP_EOL . PHP_EOL, FILE_APPEND);
            }
        }
        else
        {
            file_put_contents(Log::$LOG['logfile'],  date('Y-m-d H:i:s') . ':用户' . $searchName . '回退失败' . PHP_EOL . PHP_EOL, FILE_APPEND);
        }
    }

    public static function pregDetail($searchName)
    {
        $file = './data/' . $searchName . '_detail.html';
        if (is_file($file))
        {
            $userInfo = self::getUserDetail($file);
            return $userInfo;
        }
        else
        {
            self::rollBackUser($searchName , 0);
        }
    }
    public static function getUserDetail($file)
    {
        /**
         *  用户信息获取
         */
        $user = [];
        $pre = array(" ","　","\t","\n","\r","\\r","\\t","\\n");
        $rep = array('','','','','','');
        $data = str_replace($pre, $rep, file_get_contents($file));

        /*$uname = '/<title>.*<\/title>/';
        preg_match($uname, $data, $uinfo);
        $uinfo = implode('', $uinfo);
        //var_dump( str_replace('的微博_微博', '', strip_tags($uinfo)));
        $uinfo = str_replace('的微博_微博', '', strip_tags($uinfo));
        $user['n_name'] = $uinfo;*/


        /*$guan = '/<strong class=\\\".{0,10}\\\">[0-9]*<\\\\\/strong><span class=\\\".{0,10}\\\">关注<\\\\\/span>/x';
        preg_match($guan, $data, $uinfo);
        $uinfo = implode('', $uinfo);
        //var_dump(str_replace('关注', '', strip_tags($uinfo)));
        $uinfo = str_replace('关注', '', strip_tags($uinfo));
        $user['attention'] = empty($uinfo) ? 0 : $uinfo;*/


        /*$fen = '/<strong class=\\\".{0,10}\\\">[0-9]*<\\\\\/strong><span class=\\\".{0,10}\\\">粉丝<\\\\\/span>/x';
        preg_match($fen, $data, $uinfo);
        $uinfo = implode('', $uinfo);
        //var_dump(str_replace('粉丝', '', strip_tags($uinfo)));
        $uinfo = str_replace('粉丝', '', strip_tags($uinfo));
        $user['fans'] = empty($uinfo) ? 0 : $uinfo;*/


        /*$wei = '/<strong class=\\\".{0,10}\\\">[0-9]*<\\\\\/strong><span class=\\\".{0,10}\\\">微博<\\\\\/span>/x';
        preg_match($wei, $data, $uinfo);
        $uinfo = implode('', $uinfo);
        //var_dump(str_replace('微博', '', strip_tags($uinfo)));
        $uinfo = str_replace('微博', '', strip_tags($uinfo));
        $user['weibo_count'] = empty($uinfo) ? 0 : $uinfo;*/

        $gender = '/<spanclass=\\\"pt_titleS_txt2\\\">性别：<\\\\\/span><spanclass=\\\"pt_detail\\\">.{0,10}<\\\\\/span>/x';
        preg_match($gender, $data, $uinfo);
        $uinfo = implode('', $uinfo);
        $uinfo = str_replace('性别：', '', strip_tags($uinfo));
        $user['gender'] = empty($uinfo) ? '' : $uinfo;

        $place = '/<spanclass=\\\"pt_titleS_txt2\\\">所在地：<\\\\\/span><spanclass=\\\"pt_detail\\\">.{0,20}<\\\\\/span>/x';
        preg_match($place, $data, $uinfo);
        $uinfo = implode('', $uinfo);
        $uinfo = str_replace('所在地：', '', strip_tags($uinfo));
        $user['come_from'] = empty($uinfo) ? '' : $uinfo;

        $register = '/<spanclass=\\\"pt_titleS_txt2\\\">注册时间：<\\\\\/span><spanclass=\\\"pt_detail\\\">.{0,12}<\\\\\/span>/x';
        preg_match($register, $data, $uinfo);
        $uinfo = implode('', $uinfo);
        $uinfo = str_replace('注册时间：', '', strip_tags($uinfo));
        $user['register'] = empty($uinfo) ? '1970-01-01' : $uinfo;

        $university = '/<spanclass=\\\"pt_titleS_txt2\\\">大学：<\\\\\/span><spanclass=\\\"pt_detail\\\"><ahref=\\\".{0,200}\\\">.{0,50}<\\\\\/a>/x';
        preg_match($university, $data, $uinfo);
        $uinfo = implode('', $uinfo);
        $uinfo = str_replace('大学：', '', strip_tags($uinfo));
        $user['university'] = empty($uinfo) ? '' : $uinfo;

        $birthday = '/<spanclass=\\\"pt_titleS_txt2\\\">生日：<\\\\\/span><spanclass=\\\"pt_detail\\\">.{0,20}<\\\\\/span>/x';
        preg_match($birthday, $data, $uinfo);
        $uinfo = implode('', $uinfo);
        $rep = ['生日：', '年', '月', '日'];
        $pla = ['', '-', '-', ''];
        $uinfo = str_replace($rep, $pla, strip_tags($uinfo));
        $user['birthday'] = empty($uinfo) ? '' : $uinfo;

        $discribe = '/<spanclass=\\\"pt_titleS_txt2\\\">简介：<\\\\\/span><spanclass=\\\"pt_detail\\\">.{0,1000}<\\\\\/span>/Ux';
        preg_match($discribe, $data, $uinfo);
        $uinfo = implode('', $uinfo);
        $uinfo = str_replace('简介：', '', strip_tags($uinfo));
        $user['discribe'] = empty($uinfo) ? '' : $uinfo;

        $company = '/<spanclass=\\\"pt_titleS_txt2\\\">公司：<\\\\\/span><spanclass=\\\"pt_detail\\\"><ahref=\\\".{0,300}\\\">.{0,40}<\\\\\/a>/x';
        preg_match($company, $data, $uinfo);
        $uinfo = implode('', $uinfo);
        $uinfo = str_replace('公司：', '', strip_tags($uinfo));
        $user['company'] = empty($uinfo) ? '' : $uinfo;

        return $user;

    }
}